package com.github.beihaifeiwu.myspring.http.feign;

import feign.RequestTemplate;
import feign.codec.EncodeException;
import feign.codec.Encoder;
import feign.form.FormEncoder;
import org.springframework.web.multipart.MultipartFile;

import java.lang.reflect.Type;
import java.util.Collections;
import java.util.Map;

/**
 * Created by liupin on 2017/9/6.
 */
public class SpringFormEncoder extends FormEncoder {

    private final SpringMultipartEncodedDataProcessor multipartProcessor =
            new SpringMultipartEncodedDataProcessor();

    public SpringFormEncoder(Encoder delegate) {
        super(delegate);
    }

    @Override
    public void encode(Object object, Type bodyType, RequestTemplate template) throws EncodeException {
        if (!bodyType.equals(MultipartFile.class)) {
            super.encode(object, bodyType, template);
            return;
        }

        MultipartFile file = (MultipartFile) object;
        Map<String, Object> data = Collections.singletonMap(file.getName(), object);
        multipartProcessor.process(data, template);
    }

}
